package worklog.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import worklog.db.UserDB;

import worklog.dto.ResponseDTO;
import worklog.dto.UserDTO;

@WebServlet("/updateUser")
public class UpdateUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserDB userDB;
	private ResponseDTO responder = new ResponseDTO();

    public UpdateUser() { super(); }
    
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
		//doGet(request, response); 
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		userDB = new UserDB();
		PrintWriter out = response.getWriter();
		response.setContentType("application/json");
    	out.print(processRequest(request));
    	userDB.close();
    	out.close();
	}
	
	private String processRequest(HttpServletRequest request){
		HttpSession session = request.getSession();
		
		if (session.getAttribute("logged") == null || (Boolean)session.getAttribute("logged") != true) return responder.showAuthError();
		int adminId = (Integer) session.getAttribute("userId");
		Boolean isAdmin = userDB.isAdmin(adminId);
			
		int paramLength = request.getParameterMap().size(), userId, res;
		String userLogin, userEmail, userIdStr, userStatusStr, userPass, oldPass;
		UserDTO user = new UserDTO();
        		
    	if (paramLength > 0) {
    		userIdStr = request.getParameter("id");
			userLogin = request.getParameter("login");
			userEmail = request.getParameter("email");
			userPass = request.getParameter("password");
			oldPass = request.getParameter("oldPass");
			userStatusStr = request.getParameter("status");
			
			if (userIdStr == null) return responder.showError("User ID is empty"); 
			if (userLogin == null && userEmail == null && userPass == null) 
				return responder.showError("There is nothing to edit");
			
			try{ userId = Integer.parseInt(userIdStr); }
			catch(NumberFormatException e){ userId = -1; }
			if (userId == -1) return responder.showError("Incorrect user ID");


			user = userDB.getUserById(userId);
			if (user == null) return responder.showError("User does not exist");
			
			if (userPass != null) {
				if (isAdmin != true && adminId != userId){					// only admin or user himself can change his password
					return responder.showError("Access denied!");
				}
				
				if (isAdmin != true && oldPass != null){					// not admin - check old password
					Boolean oldPassCorrect = userDB.checkUserPassword(userId, oldPass);
					if (!oldPassCorrect) return responder.showError("Old password is incorrect!");
				}					
				user.setPassword(userPass);
				res = userDB.updateUserPassword(user);
			}
			else {
				if (isAdmin == false) return responder.showError("Access denied!");
				
				if (userLogin != null) user.setLogin(userLogin);
				if (userEmail != null) user.setEmail(userEmail);
				if (userStatusStr != null){
					int userStatus = 1;
					try{ userStatus = Integer.parseInt(userStatusStr); } catch(NumberFormatException e){ }
					user.setStatus(userStatus);
				}
				res = userDB.updateUser(user);
			}
			
			user.setPassword("");						// don't show the password in the response
			
			if (res == -1) return responder.showError("DB error");
			else return user.toString();
    	}	
		return responder.showError();
	}
}
